import router from '@/router/index'
import { getToken } from '@/utils/auth'
// 导入
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'
import store from '@/store/index'

const whiteList = ['/login']

const modules = import.meta.glob('../**/**/**.vue')

const readNodes = (nodes = [], routerInfo, parent) => {
  nodes.forEach((res) => {
    let name = ''
    const path = res?.component
    res.component = modules[`../${path}.vue`]
    if (parent) {
      routerInfo.addRoute(parent, res)
    } else {
      name = res.name
      routerInfo.addRoute(res)
    }
    if (res.children && res.children.length) readNodes(res.children, router, name)
  })
}
/**
 * 路由守卫
 */
router.beforeEach((to, form, next) => {
  document.title = ''
  to.matched.forEach((item) => {
    document.title = `${item.meta.title || ''}`
  })
  NProgress.start()
  const hasToken = getToken()
  if (hasToken) {
    if (to.path === '/login') {
      // 已登录访问Login跳转首页
      next({ path: '/' })
      NProgress.done()
    } else {
      try {
        if (store.getters.userInfo.userName) {
          if (router.defaultRouters.length === router.getRoutes().length) {
            store.dispatch('user/getUserInfo').then(() => {
              readNodes(store.getters.role.menulist, router)
              next({ path: to.fullPath, replace: true })
            })
          } else {
            next()
          }
        } else {
          store.dispatch('user/getUserInfo').then(() => {
            readNodes(store.getters.role.menulist, router)
            next({ path: '/', replace: true })
          })
        }
      } catch (error) {
        next(`/login?redirect=${to.path}`)
        NProgress.done()
      }
    }
  } else if (whiteList.includes(to.path)) {
    next()
  } else {
    next(`/login?redirect=${to.path}`)
    NProgress.done()
  }
})

router.afterEach(() => {
  NProgress.done()
})
